import React, { useState } from 'react'
import { DesktopOutlined, FileOutlined, PieChartOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { Menu } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'

type MenuItem = Required<MenuProps>['items'][number]

const items: MenuItem[] = [
  {
    label: '栏目一',
    key: '/page1',
    icon: <PieChartOutlined />
  },
  {
    label: '栏目二',
    key: '/page2',
    icon: <DesktopOutlined />
  },
  {
    label: '栏目三',
    key: '/page3',
    icon: <UserOutlined />,
    children: [
      {
        label: '栏目301',
        key: '/page3/page301'
      },
      {
        label: '栏目302',
        key: '/page3/page302'
      }
    ]
  },
  {
    label: '栏目四',
    key: '/page4',
    icon: <TeamOutlined />,
    children: [
      {
        label: '栏目401',
        key: '/page4/page401'
      },
      {
        label: '栏目402',
        key: '/page4/page402'
      }
    ]
  }
]

const Comp: React.FC = () => {
  const navigateTo = useNavigate()
  const { pathname: currentRoute } = useLocation()

  let firstOpenKey: string = ''

  function findKey(obj: any) {
    return obj.key === currentRoute
  }

  for (let i = 0; i < items.length; i++) {
    if (items[i]!['children'] && items[i]!['children'].find(findKey)) {
      firstOpenKey = items[i]!.key as string
      break
    }
  }

  const menuClick = (e: { key: string }) => {
    navigateTo(e.key)
  }

  const [openKeys, setOpenKeys] = useState([firstOpenKey])
  const onOpenChange: MenuProps['onOpenChange'] = (keys: string[]) => {
    setOpenKeys([keys[keys.length - 1]])
  }

  return <Menu theme='dark' defaultSelectedKeys={[currentRoute]} mode='inline' items={items} openKeys={openKeys} onClick={menuClick} onOpenChange={onOpenChange} />
}

export default Comp
